package etnorservice.etnor_service.mapper.projectMapper;

import etnorservice.etnor_service.domain.Project;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ProjectMapper {
    @Insert("INSERT INTO projects(name, description, creator_id, is_free, price, cover_image, file_path, file_size, version, created_at, updated_at, status) " +
            "VALUES(#{name}, #{description}, #{creatorId}, #{isFree}, #{price}, #{coverImage}, #{filePath}, #{fileSize}, #{version}, NOW(), NOW(), #{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Project project);

    @Select("SELECT * FROM projects WHERE id = #{id} AND status != 'deleted'")
    Project findById(Long id);

    @Select("SELECT * FROM projects WHERE creator_id = #{creatorId} AND status != 'deleted' ORDER BY created_at DESC")
    List<Project> findByCreatorId(Long creatorId);

    @Select("SELECT * FROM projects  ORDER BY created_at DESC LIMIT #{offset}, #{limit}")
    List<Project> findAllPublished(@Param("offset") int offset, @Param("limit") int limit);

    @Select("SELECT * FROM projects WHERE status = 'published' AND is_free = #{isFree} ORDER BY created_at DESC LIMIT #{offset}, #{limit}")
    List<Project> findByIsFree(@Param("isFree") boolean isFree, @Param("offset") int offset, @Param("limit") int limit);

    @Update("UPDATE projects SET name = #{name}, description = #{description}, is_free = #{isFree}, price = #{price}, " +
            "cover_image = #{coverImage}, file_path = #{filePath}, file_size = #{fileSize}, version = #{version}, " +
            "updated_at = NOW(), status = #{status} WHERE id = #{id}")
    int update(Project project);

    @Update("UPDATE projects SET status = 'deleted', updated_at = NOW() WHERE id = #{id}")
    int delete(Long id);

    @Update("UPDATE projects SET download_count = download_count + 1 WHERE id = #{id}")
    int incrementDownloadCount(Long id);

    @Update("UPDATE projects SET view_count = view_count + 1 WHERE id = #{id}")
    int incrementViewCount(Long id);

    @Select("SELECT COUNT(*) FROM projects WHERE status = 'published'")
    int countAllPublished();

    @Select("SELECT COUNT(*) FROM projects WHERE creator_id = #{creatorId} AND status != 'deleted'")
    int countByCreatorId(Long creatorId);
}